<!-- 设备保养计划 -->
<template>
  <div class="maintenance-plan">
    <a-button type="outline" @click="add">
      <template #icon>
        <icon-plus />
      </template>
      <template #default>添加计划</template>
    </a-button>
    <TableTurn
      :table-data="getData"
      :args="args"
      :style="{
        marginTop: '20px',
      }"
      :is-show-pagination="false"
      ref="tableRef"
    >
      <a-table-column :width="100" align="center" title="是否启用">
        <template #cell="{ record }">
          <icon-check-circle
            class="icon"
            :class="record.isEnable ? 'open' : 'close'"
          />
        </template>
      </a-table-column>
      <a-table-column
        :width="150"
        align="center"
        title="保养计划名称"
        data-index="planName"
      >
      </a-table-column>
      <a-table-column :width="200" align="center" title="保养内容">
        <template #cell="{ record }">
          <a-textarea v-model="record.planContent" auto-size disabled />
        </template>
      </a-table-column>
      <a-table-column :width="200" align="center" title="保养标准">
        <template #cell="{ record }">
          <a-textarea v-model="record.planStandard" auto-size disabled />
        </template>
      </a-table-column>
      <a-table-column :width="150" align="center" title="保养周期">
        <template #cell="{ record }">
          {{
            `${record.maintenanceCycleNum}/${sumFn(
              record.maintenanceCycleUnit
            )}`
          }}
        </template>
      </a-table-column>
      <a-table-column :width="150" align="center" title="保养到期预警">
        <template #cell="{ record }">
          {{
            `${record.maintenanceWarning}/${sumFn(record.maintenanceCycleUnit)}`
          }}
        </template>
      </a-table-column>
      <a-table-column :width="150" align="center" title="是否默认">
        <template #cell="{ record }">
          {{ record.isEnable ? '是' : '否' }}
        </template>
      </a-table-column>
      <a-table-column align="center" :width="300" fixed="right" title="操作">
        <template #cell="{ record }">
          <a-button type="text" @click="goEdit(record)">编辑</a-button>
          <a-popconfirm
            @ok="deleteItem(record.id)"
            content="确定删除吗"
            type="error"
          >
            <a-button
              type="text"
              :style="{
                color: 'red',
              }"
              >删除</a-button
            >
          </a-popconfirm>
        </template>
      </a-table-column>
    </TableTurn>

    <planModal
      :type="type"
      :form="currForm.list"
      v-model:visible="modalVisible"
      @equipmentEmit="equipmentEmit"
    >
    </planModal>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed } from 'vue';
  import {
    GetEquipmentPlan,
    PostEquipmentPlan,
    PutEquipmentPlan,
    DelEquipmentPlan,
  } from '@/api/equipment-management/equipment-list';
  import { useRoute } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import planModal from '../../../../components/equipment-repair/index.vue';

  const props = withDefaults(
    defineProps<{
      equipmentId: number;
    }>(),
    {}
  );
  const route = useRoute();
  // 表格配置
  const args = reactive({
    stripe: true,
    bordered: {
      headerCell: true,
    },
  });

  let tableRef = ref(); // 储存table的ref

  const id = Number(route.query.id); // 设备id

  // 储存某一行的值
  const currForm = reactive({
    list: {
      planName: '', // 保养计划名称
      planContent: '', // 保养内容
      isEnable: 1, // 是否启用
      maintenanceCycleNum: null, // 保养周期值
      maintenanceCycleUnit: null, // 保养周期单位
      planStandard: '', // 保养标准
      maintenanceWarning: 0, // 保养到期预警时间
    },
  });

  let type = ref(0); // 判断弹出框的类型
  let modalVisible = ref(false); // 判断弹出框是否弹出
  let currOpenId = 0; // 储存当前启用状态的id

  // 添加计划
  const add = () => {
    type.value = 10;
    modalVisible.value = true;
  };
  const emuipmentAge = [
    {
      value: 1,
      label: '时间',
      children: [
        { value: 3, label: '天' },
        { value: 2, label: '月' },
        { value: 1, label: '年' },
      ],
    },
    {
      value: 4,
      label: '数量',
      children: [
        { value: 4, label: '件' },
        { value: 5, label: '个' },
        { value: 6, label: '条' },
        { value: 7, label: '台' },
      ],
    },
  ];
  const sumFn = (sum: number) => {
    if (sum > 3) {
      return emuipmentAge[1].children.filter((ele) => ele.value === sum)[0]
        ?.label;
    } else {
      return emuipmentAge[0].children.filter((ele) => ele.value === sum)[0]
        ?.label;
    }
  };
  // 获取表格数据
  const getData = async (pageData?: any) => {
    try {
      const res = await GetEquipmentPlan({
        equipId: props.equipmentId,
        ...pageData,
      });

      // 查找当前启用保养计划的id
      // for (let i of res) {
      //   if (i.isEnable === 1) {
      //     currOpenId = i.id;
      //     break;
      //   }
      // }

      return Promise.resolve(res);
    } catch (error: unknown) {
      console.log(error);
    }
  };

  // 修改启用状态
  const changeState = async (record: any) => {
    try {
      if (record.id === currOpenId) Message.error('至少启用一条保养计划！');
      else {
        record.isEnable = !record.isEnable;
        await PostEquipmentPlan(record);
        currOpenId = record.id;
        tableRef.value.loadData();
      }
    } catch (error: unknown) {
      console.log(error);
    }
  };

  // 编辑按钮
  const goEdit = (record: any) => {
    currForm.list = record;
    type.value = 11;
    modalVisible.value = true;
  };

  // 删除一项
  const deleteItem = async (id: number) => {
    try {
      await DelEquipmentPlan({ id });
      tableRef.value.loadData();
    } catch (error: unknown) {
      console.log(error);
    }
  };

  // 弹出框的自定义事件
  const equipmentEmit = async (list: any, type: number) => {
    try {
      if (type === 10) {
        await PostEquipmentPlan({ ...list, equipmentId: props.equipmentId });
      } else if (type === 11) {
        await PutEquipmentPlan({ ...list, equipmentId: props.equipmentId });
      }
      currForm.list = {
        planName: '', // 保养计划名称
        planContent: '', // 保养内容
        isEnable: 1, // 是否启用
        maintenanceCycleNum: null, // 保养周期值
        maintenanceCycleUnit: null, // 保养周期单位
        planStandard: '', // 保养标准
        maintenanceWarning: 0, // 保养到期预警时间
      };
      modalVisible.value = false;
      tableRef.value.loadData();
    } catch (error: unknown) {
      console.log(error);
    }
  };
</script>

<style scoped lang="less">
  .maintenance-plan {
    padding: 0 40px;
    .icon {
      font-size: 30px;
      cursor: pointer;
    }
    .open {
      color: #165dff;
    }
    .close {
      color: #ccc;
    }
    :deep(.arco-textarea[disabled]) {
      -webkit-text-fill-color: #000;
      background-color: #fff;
    }
  }
</style>
